package cn.com.dhcc.ddi.datamapping.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.vo.UserInfoVo;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.tag.staticcode.StaticCode;
import cn.com.dhcc.ddi.datamapping.dao.FuncMappingDao;
import cn.com.dhcc.ddi.datamapping.service.DataMappingService;
import cn.com.dhcc.ddi.datamapping.service.FuncIdentityService;
import cn.com.dhcc.ddi.datamapping.vo.DataMapping;
import cn.com.dhcc.ddi.datamapping.vo.FuncIdentify;
import cn.com.dhcc.ddi.datamapping.vo.FuncMapping;
import cn.com.dhcc.ddi.datasource.service.DataSourceService;
import cn.com.dhcc.ddi.datasource.service.TableColService;
import cn.com.dhcc.ddi.datasource.service.TableInfoService;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.datasource.vo.TableColVo;
import cn.com.dhcc.ddi.datasource.vo.TableInfoVo;
import cn.com.dhcc.ddi.task.service.TaskService;
import cn.com.dhcc.ddi.task.vo.Task;

/**
 * 
 * @ClassName: DataMappingController
 * @Description: 数据源映射管理
 * @author fxx
 * @date 2016-12-7
 * 
 */
@Controller
@RequestMapping(value="/data_mapping")
public class DataMappingController extends BaseController {
	private static Logger logger = Log.getLogger(LOGTYPE.DDI);
	@Autowired
	DataSourceService dataSourceService;
	@Autowired
	FuncIdentityService funcIdentityService;
	@Autowired
	TableInfoService tableInfoService;
	@Autowired
	TableColService tableColService;
	@Autowired
	DataMappingService dataMappingService;
	@Autowired
	TaskService taskService;
	@Autowired
	FuncMappingDao funcMappingDao;
	@Autowired
	CmUserMgrService userMgrService;
	
	/**
	 * 
	 * @Title: list
	 * @Description: 数据源映射列表
	 * @param @param model
	 * @param @param pager
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_list")
	public String list(Model model, Pager pager, String mappingName, HttpSession httpSession){
		try {
			WhereCondition searchParameter = new WhereCondition();
			searchParameter.where1Eq1();
			if (StrUtil.isNotBank(mappingName)) {
				searchParameter.and().like("t1.mapping_name", "%"+mappingName+"%");
			}
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			UserInfoVo currentUser = userMgrService.getUserById(userId);
			model.addAttribute("currentUser", currentUser);
			if (!isAdmin) {
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					if (StrUtil.isNotBank(nodeIdsStr)) {
						String[] nodeIds = nodeIdsStr.split(",");
						searchParameter.andIn("t2.node_id", nodeIds);
						searchParameter.andIn("t3.node_id", nodeIds);
					} else {
						searchParameter.andEq("1", "2");
					}
				}
			}
			searchParameter.orderBy("t1.mtime desc");
			PagerData<DataMapping> datas = dataMappingService.getPagerList(pager, searchParameter);
			model.addAttribute(DATA_KEY, datas.getDatas());
			setTotoal(model, datas.getTotal());
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "datamapping/data_mapping_list";
	}
	
	/**
	 * 
	 * @Title: add
	 * @Description: 数据源映射添加页面
	 * @param @param model
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_add")
	public String add(Model model, HttpSession httpSession){		
		try {
			WhereCondition condition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			UserInfoVo currentUser = userMgrService.getUserById(userId);
			if (!isAdmin) {
				if (currentUser != null) {
					String nodeIdsStr = currentUser.getExt2();
					if (StrUtil.isNotBank(nodeIdsStr)) {
						String[] nodeIds = nodeIdsStr.split(",");
						condition.andIn("node_id", nodeIds);
					} else {
						condition.andEq("1", "2");
					}
				}
			}
			List<DataSourceVo> datas = dataSourceService.getDsList(condition);
			model.addAttribute("dsData", datas);
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "datamapping/data_mapping_add";
	}
	
	/**
	 * 
	 * @Title: add
	 * @Description: 添加数据源映射
	 * @param @param vo
	 * @param @param funcMappingList
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/add_data_mapping")
	@ResponseBody
	public Map<String, Object> add(DataMapping vo, String funcMappingList) {
		try {
			vo.setMtime(new Date());
			vo.setStatus("1");
			dataMappingService.batchInsert(vo, funcMappingList);			
			return jsonSuccessResult("添加成功");
		} catch (ServiceException e) {
			logger.error("添加失败", e);
			return jsonFailResult("添加失败");
		}
	}
	
	/**
	 * 
	 * @Title: addMappingModel
	 * @Description: 添加映射规则页面
	 * @param @param model
	 * @param @param srcDsId
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_rule_add")
	public String addMappingModel(Model model, String srcDsId){
		
		return "datamapping/data_mapping_rule_add";
	}
	
	/**
	 * 
	 * @Title: chooseMappingModel
	 * @Description: 选择映射规则页面
	 * @param @param model
	 * @param @param srcDsId
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_rule_choose")
	public String chooseMappingModel(Model model, String srcDsId, String mappingType){
		try {
			WhereCondition condition = new WhereCondition();
			BetweenValue betweenValue = null;
			if (mappingType.equals("1")) {
				betweenValue = new BetweenValue("1", "6", true, true);
			}
			if (mappingType.equals("2")) {
				
			}
			if (mappingType.equals("3")) {
				betweenValue = new BetweenValue("6", "7", false, true);
			}
			condition.andBetween("t1.fx_type", betweenValue);
			condition.orderBy("t1.fx_type,t1.fx_name_en");
			List<FuncIdentify> datas = funcIdentityService.getList(condition);
			model.addAttribute(DATA_KEY, JsonUtil.toJson(datas));
			//数据源及表信息
			DataSourceVo vo = dataSourceService.getDataSourceById(srcDsId);
			String dsId = vo.getId();
			List<TableInfoVo> tableInfoList = tableInfoService.getTableInfoByDsId(dsId);
			for (int i = 0; i < tableInfoList.size(); i++) {
				String tableId = tableInfoList.get(i).getId();
				List<TableColVo> tableColList = tableColService.getColsByTableId(tableId);
				tableInfoList.get(i).setTableColVos(tableColList);
			}
			model.addAttribute(VO_KEY, vo);
			model.addAttribute("tableInfoList", JsonUtil.toJson(tableInfoList));
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
		
		return "datamapping/data_mapping_rule_choose";
	}
	
	/**
	 * 
	 * @Title: delete
	 * @Description: 删除数据映射
	 * @param @param model
	 * @param @param id
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/data_mapping_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(Model model, String id) {
		try { 
			WhereCondition condition = new WhereCondition();
			condition.where().eq("mp_id", id);
			condition.and().eq("status", "1");
			List<Task> task = taskService.getTasks(condition);
			if (task.size() == 0) {
				List<String> fxIds = funcMappingDao.getIdsByMappingId(id);
				dataMappingService.delete(id);
				for (int i = 0; i < fxIds.size(); i++) {
					funcMappingDao.delete(fxIds.get(i));
				}
				return jsonSuccessResult("删除成功");
			}else{
				return jsonFailResult("当前数据映射已关联任务，无法删除！");
			}
		} catch (Exception e) {
			logger.error("删除失败", e);
			return jsonFailResult("删除失败");
		}
	}
	
	/**
	 * 
	 * @Title: realtimePreview
	 * @Description: 实时预览
	 * @param @param model
	 * @param @param srcDsId
	 * @param @param funcMappingList
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_realtime_preview")
	@ResponseBody
    public Map<String, Object> realtimePreview(Model model, String srcDsId, String funcMappingList){
	    String msg = "";
	    try {
	    	List<FuncMapping> funcMList = dataMappingService.getfuncMappingList(funcMappingList);
	    	Map<String, Map<String, Object>> tableMappingMap = dataMappingService.realtimePreview(srcDsId, funcMList);
			msg = "实时预览成功";
			return jsonSuccessDataResult(msg, tableMappingMap);
		} catch (Exception e) {
			msg = "实时预览失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
    }  
	
	/**
	 * 
	 * @Title: get
	 * @Description: 查看数据源映射信息
	 * @param @param model
	 * @param @param id
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_get")
	public String get(Model model,String id, HttpSession httpSession){
		try {
			model = getDataMappingModel(model, id, httpSession);
		} catch (Exception e) {
			logger.error("查看数据源映射信息失败", e);
			return toAlertPage(model, "查看数据源映射信息失败");
		}
		return "datamapping/data_mapping_get";
	}
	
	/**
	 * 
	 * @Title: update
	 * @Description: 数据源映射更新页面
	 * @param @param model
	 * @param @param id
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value="/data_mapping_update")
	public String update(Model model,String id, HttpSession httpSession){
		try {
			model = getDataMappingModel(model, id,httpSession);
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "datamapping/data_mapping_update";
	}
	
	/**
	 * 
	 * @Title: update
	 * @Description: 更新数据源映射
	 * @param @param vo
	 * @param @param funcMappingList
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/update_data_mapping")
	@ResponseBody
	public Map<String, Object> update(DataMapping vo, String funcMappingList) {
		try {
			vo.setMtime(new Date());
			dataMappingService.update(vo, funcMappingList);			
			return jsonSuccessResult("更新成功");
		} catch (Exception e) {
			logger.error("更新失败", e);
			return jsonFailResult("更新失败");
		}
	}
	
	/**
	 * 
	 * @Title: lock
	 * @Description: 停用
	 * @param @param id
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
    @RequestMapping(value="/lock_data_mapping")
	@ResponseBody
	public Map<String, Object> lock(String id){
		String status = StaticCode.DATA_STATUS.DISABLE.getCode();
		try {
			DataMapping obj = dataMappingService.get(id);
			obj.setStatus(status);
			obj.setMtime(new Date());
			dataMappingService.update(obj);
			return jsonSuccessResult("停用成功");
		} catch (ServiceException e) {
			logger.error("停用失败", e);
			return jsonFailResult("停用失败");
		}
	}
	
	/**
	 * 
	 * @Title: unlock
	 * @Description: 启用
	 * @param @param id
	 * @param @return 参数
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(value="/unlock_data_mapping")
	@ResponseBody
	public Map<String, Object> unlock(String id){
		String status = StaticCode.DATA_STATUS.ENABLE.getCode();
		try {
			DataMapping obj = dataMappingService.get(id);
			obj.setStatus(status);
			obj.setMtime(new Date());
			dataMappingService.update(obj);
			return jsonSuccessResult("启用成功");
		} catch (ServiceException e) {
			logger.error("启用失败", e);
			return jsonFailResult("启用失败");
		}
	}
	
	/**
	 * 名称唯一性
	 * 
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("/is_mappingName_unique")
	@ResponseBody
	public String isMappingNameUnique(@RequestParam("mappingName") String newValue, @RequestParam("oldValue") String oldValue, HttpSession httpSession) {
		try {
			
			if (dataMappingService.isPropertyUnique("mapping_name", newValue, oldValue, httpSession)) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
	
	/**
	 * 
	 * @Title: getDataMappingModel
	 * @Description: 获取数据源映射信息，并存放入model，用于数据源映射查看和更新
	 * @param @param model
	 * @param @param id
	 * @param @return 参数
	 * @return Model 返回类型
	 * @throws
	 */
	public Model getDataMappingModel(Model model, String id, HttpSession httpSession){
		try {
			//获取数据源映射对象
			DataMapping dataMapping = dataMappingService.getMappingById(id);
			//获取源端数据源信息
			WhereCondition condition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			UserInfoVo currentUser = userMgrService.getUserById(userId);
			if (!isAdmin) {
				if (currentUser != null) {
					String nodeIdsStr = currentUser.getExt2();
					if (StrUtil.isNotBank(nodeIdsStr)) {
						String[] nodeIds = nodeIdsStr.split(",");
						condition.andIn("node_id", nodeIds);
					} else {
						condition.andEq("1", "2");
					}
				}
			}
			List<DataSourceVo> datas = dataSourceService.getDsList(condition);
			
			String srcDsId = dataMapping.getSrcDsId();
			List<TableInfoVo> tableInfoList = tableInfoService.getTableInfoByDsId(srcDsId);
			for (int i = 0; i < tableInfoList.size(); i++) {
				String tableId = tableInfoList.get(i).getId();
				List<TableColVo> tableColList = tableColService.getColsByTableId(tableId);
				tableInfoList.get(i).setTableColVos(tableColList);
			}
			//获取函数映射对象
			List<FuncMapping> funcMappings = funcMappingDao.getList(id);
			for (FuncMapping funcM:funcMappings) {
				String fxId = funcM.getFxId();
				FuncIdentify funcIdentify = funcIdentityService.getById(fxId);
				funcM.setFuncIdentify(funcIdentify);			        
			}
			Map<String,Map<String, Object>> tableMappingMap = dataMappingService.realtimePreview(srcDsId, funcMappings);
			model.addAttribute(VO_KEY, dataMapping);
			model.addAttribute("dsData", datas);
			model.addAttribute("funcMappings", funcMappings);
			model.addAttribute("tableInfoList", tableInfoList);
			model.addAttribute("tableMappingMap", JsonUtil.toJson(tableMappingMap));
		} catch (Exception e) {
			logger.error("获取数据源映射信息失败", e);
		}
		return model;
	}

}
